// 请将这段代码作为你的最终版本，然后专注于排查上面提到的 1-4 点。
package com.daily.daily_push.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

public class DifyJsonlUploaderDefinitive {

    // --- 1. 请再次确认这里的每一个字符都是正确的 ---
    private static final String DIFY_BASE_URL = "http://localhost/v1";
    private static final String DATASET_ID = "610a5388-806d-4ed2-bafa-5e3b6494ef45";
    private static final String API_KEY = "dataset-e9njBMeGxrHx4b2dRIJThTGr";
    private static final String JSONL_FILE_PATH = "D:\\TestFile\\商管问答知识库模板.docx";
    // --- 配置结束 ---

    public static void main(String[] args) {
        try {
            uploadAndCreateDocument();
        } catch (IOException e) {
            System.err.println("发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void uploadAndCreateDocument() throws IOException {
        System.out.println("--- 开始上传文件并创建文档 (最终版) ---");

        String processRuleJson = buildProcessRuleJsonWithPojo();
        System.out.println("生成的请求数据: " + processRuleJson);

        String boundary = "Boundary-" + UUID.randomUUID().toString();
        String CRLF = "\r\n";

        URL url = new URL(DIFY_BASE_URL + "/datasets/" + DATASET_ID + "/document/create-by-file");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // --- 这是整个请求的 Main Headers ---
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Bearer " + API_KEY);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        connection.setUseCaches(false);
        // --- Main Headers 设置结束 ---

        try (DataOutputStream requestStream = new DataOutputStream(connection.getOutputStream())) {
            // --- 这是第一个部分的 Part Headers 和内容 ---
            requestStream.writeBytes("--" + boundary + CRLF);
            requestStream.writeBytes("Content-Disposition: form-data; name=\"data\"" + CRLF);
            requestStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + CRLF);
            requestStream.writeBytes(CRLF);
            requestStream.write(processRuleJson.getBytes(StandardCharsets.UTF_8));
            requestStream.writeBytes(CRLF);
            // --- 第一个部分结束 ---

            // --- 这是第二个部分的 Part Headers 和内容 ---
            Path filePath = Paths.get(JSONL_FILE_PATH);
            String fileName = filePath.getFileName().toString();
            requestStream.writeBytes("--" + boundary + CRLF);
            requestStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"" + CRLF);
            requestStream.writeBytes("Content-Type: application/json; charset=UTF-8" + CRLF);
            requestStream.writeBytes(CRLF);

            Files.copy(filePath, requestStream);

            requestStream.writeBytes(CRLF);
            // --- 第二个部分结束 ---

            // --- 整个请求的结束符 ---
            requestStream.writeBytes("--" + boundary + "--" + CRLF);
            requestStream.flush();
        }

        int responseCode = connection.getResponseCode();
        System.out.println("响应状态码: " + responseCode);

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                (responseCode >= 200 && responseCode < 300) ? connection.getInputStream() : connection.getErrorStream()
        ))) {
            StringBuilder responseBody = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                responseBody.append(line);
            }
            System.out.println("响应体: " + responseBody.toString());

            if (responseCode >= 200 && responseCode < 300) {
                System.out.println("文件上传成功！文档已创建。");
            } else {
                System.err.println("文件上传失败！");
            }
        } finally {
            connection.disconnect();
        }
    }


    public static String buildProcessRuleJsonWithPojo() {
        Segmentation segmentation = new Segmentation("\n", 500);
        Rule rule = new Rule(segmentation);
        ProcessRule processRule = new ProcessRule("custom", rule);
        ProcessRuleRequest requestData = new ProcessRuleRequest("economy", processRule);
        Gson gson = new GsonBuilder().create();
        return gson.toJson(requestData);
    }
}

// 加上了 Getter，这是更好的编程习惯
class ProcessRuleRequest {
    private final String indexing_technique;
    private final ProcessRule process_rule;

    public ProcessRuleRequest(String indexing_technique, ProcessRule process_rule) {
        this.indexing_technique = indexing_technique;
        this.process_rule = process_rule;
    }
    public String getIndexing_technique() { return indexing_technique; }
    public ProcessRule getProcess_rule() { return process_rule; }
}

class ProcessRule {
    private final String mode;
    private final Rule rules;

    public ProcessRule(String mode, Rule rules) {
        this.mode = mode;
        this.rules = rules;
    }
    public String getMode() { return mode; }
    public Rule getRules() { return rules; }
}

class Rule {
    private final Segmentation segmentation;

    public Rule(Segmentation segmentation) {
        this.segmentation = segmentation;
    }
    public Segmentation getSegmentation() { return segmentation; }
}

class Segmentation {
    private final String separator;
    private final int max_tokens;

    public Segmentation(String separator, int max_tokens) {
        this.separator = separator;
        this.max_tokens = max_tokens;
    }
    public String getSeparator() { return separator; }
    public int getMax_tokens() { return max_tokens; }
}